from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel
from typing import Optional
import uuid
import base64
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont
import random
import string

router = APIRouter()

# 模拟验证码存储
captcha_store = {}

class LoginRequest(BaseModel):
    username: str
    password: str
    captcha: str
    rememberMe: bool = False

class LoginResponse(BaseModel):
    success: bool
    message: str
    token: Optional[str] = None

@router.post("/login", response_model=LoginResponse)
async def login(request: LoginRequest):
    """用户登录接口"""
    # 验证验证码
    if request.captcha.lower() != captcha_store.get("current", "").lower():
        return LoginResponse(success=False, message="验证码错误")
    
    # 模拟登录验证
    if request.username and request.password:
        # 这里应该调用大麦网登录API
        # 模拟成功
        token = str(uuid.uuid4())
        return LoginResponse(
            success=True, 
            message="登录成功", 
            token=token
        )
    
    return LoginResponse(success=False, message="用户名或密码错误")

@router.get("/captcha")
async def get_captcha():
    """获取验证码图片"""
    # 生成验证码
    captcha_text = ''.join(random.choices(string.ascii_uppercase + string.digits, k=4))
    captcha_store["current"] = captcha_text
    
    # 创建验证码图片
    img = Image.new('RGB', (120, 40), color='white')
    draw = ImageDraw.Draw(img)
    
    # 使用更简单的字体绘制
    try:
        font = ImageFont.load_default()
    except:
        font = None
    
    # 绘制验证码文字
    for i, char in enumerate(captcha_text):
        draw.text((20 + i * 25, 10), char, fill='black', font=font)
    
    # 添加干扰线
    for _ in range(3):
        x1, y1 = random.randint(0, 120), random.randint(0, 40)
        x2, y2 = random.randint(0, 120), random.randint(0, 40)
        draw.line([(x1, y1), (x2, y2)], fill='gray', width=1)
    
    # 转换为base64
    buffer = BytesIO()
    img.save(buffer, format='PNG')
    buffer.seek(0)
    
    return {
        "image": base64.b64encode(buffer.getvalue()).decode(),
        "text": captcha_text
    }

@router.get("/status")
async def get_login_status():
    """获取登录状态"""
    # 模拟登录状态检查
    return {"loggedIn": False, "username": None}

@router.post("/logout")
async def logout():
    """用户登出"""
    return {"success": True, "message": "登出成功"}